package com.mby.controller;

import com.mby.entity.ChatGroup;
import com.mby.entity.DeviceToken;
import com.mby.entity.Push;
import com.mby.entity.RongUser;
import com.mby.service.IPushService;
import com.mby.service.IRongYunService;
import com.mby.utils.*;
import com.mongodb.*;
import io.rong.models.message.GroupMessage;
import org.bson.Document;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by noah on 2018/4/19.
 */
@RestController
public class VehicleController extends BaseController{

    private static MongoClient client;
    private static DB db;
    private static DBCollection collection;

    @Resource
    private IPushService pushService;

    @Resource
    private IRongYunService rongYunService;

    /**
     * 根据预检单获取车辆的服务状态 “预检单”(创建预检单)-到店接车 “派工完成”(工单状态=3)-保养 “质检打印(工单状态=8)”-质检及洗车 “有结算单”-准备交车
     * get /live/service_status?precheck_id=21321
     * @param precheck_id
     */
    @GetMapping(value = "/service_status")
    public void getServiceStatus(Integer precheck_id){
        resultMap.clear();
        getEvhcMongo();
        Map<String,Date> result = new HashMap<>();
        BasicDBObject cond = new BasicDBObject();
        cond.put("_id",precheck_id);
        collection = db.getCollection("prechecks");
        DBObject precheck = collection.findOne(cond);
        if(precheck != null){
            result.put("1",(Date)precheck.get("created_at"));
            resultMap.put("status",1);
        }
        collection = db.getCollection("dispatchings");
        cond.remove("_id");
        cond.put("precheck_id",precheck_id);
        cond.put("status",8);
        DBObject dispatching = collection.findOne(cond);
        if(dispatching != null){
            result.put("2",(Date)dispatching.get("created_at"));
            resultMap.put("status",2);

            collection = db.getCollection("quality_checks");
            cond = new BasicDBObject();
            cond.put("dispatching_id",dispatching.get("_id"));
            cond.put("status",1);
            DBObject quality_check = collection.findOne(cond);
            if(quality_check != null){
                result.put("3",(Date)quality_check.get("created_at"));
                resultMap.put("status",3);
                if(getMins((Date)quality_check.get("created_at"),new Date()) >= 40){
                    result.put("4",addMins((Date)quality_check.get("created_at"),40));
                    resultMap.put("status",4);
                }
            }
        }else{
            collection = db.getCollection("dispatchings");
            cond = new BasicDBObject();
            cond.put("status",new Document("$gte",2));
            cond.put("precheck_id",precheck_id);
            dispatching = collection.findOne(cond);
            if(dispatching != null){
                result.put("2",(Date)dispatching.get("created_at"));
                resultMap.put("status",2);
            }
        }

        client.close();

        ChatGroup chatGroup = mongoTool.findOne("","{'id':"+precheck_id+"}",ChatGroup.class);
        if(chatGroup != null){
            if(chatGroup.getEstHandoverAt() != null){
                resultMap.put("est_handover_at",chatGroup.getEstHandoverDate());
            }
        }

        resultMap.put("times",result);
        respData(resultMap);
    }

    private static void getEvhcMongo(){
        //todo 需要配置多个数据源
        try {
            System.out.print("连接evhc数据库......");
            ServerAddress serverAddress = new ServerAddress(WebConstant.EVHC_DB_PATH, WebConstant.EVHC_DB_PORT);
            List<ServerAddress> address = new ArrayList<>();
            address.add(serverAddress);
            //MongoCredential credential = MongoCredential.createCredential("admin", "admin", "8022523".toCharArray());
            List<MongoCredential> credentials = new ArrayList<>();
            //credentials.add(credential);
            client = new MongoClient(address, credentials);
            db = client.getDB(WebConstant.EVHC_DB_NAME);
            collection = db.getCollection("users");
            System.out.println("成功.."+collection.count());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private long getMins(Date startDate, Date endDate){
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long diff = endDate.getTime() - startDate.getTime();
        long min = diff / nm;
        return min;
    }

    private Date addMins(Date startDate, long mins){
        long currentTime = startDate.getTime() + 40 * 60 * 1000;
        Date date = new Date(currentTime);
        return date;
    }

    /**
     * 更新预计交车时间
     * @param precheck_id
     */
    @PostMapping(value = "/est_handover_time")
    public void updateEstHandOverTime(Integer precheck_id, @RequestBody ChatGroup chatGroup) throws Exception{
        ChatGroup cg = mongoTool.findOne("","{'id':"+precheck_id+"}", ChatGroup.class);
        if(cg != null){
            mongoTool.update("{'dispatchingNo':'"+chatGroup.getDispatchingNo()+"','estHandoverDate':'"+ymdhms.format(new Date(chatGroup.getEstHandoverAt()*1000))+"','estHandoverAt':"+chatGroup.getEstHandoverAt()*1000+"}","{'id':"+precheck_id+"}",ChatGroup.class);
            respData(ok);
        }else{
            respErr("PrecheckId Not Exist");
        }
    }

    /**
     * 更新质检打印时间
     * @param precheck_id
     */
    @PostMapping(value = "/quality_check_time")
    public void updateQualityCheckime(Integer precheck_id, @RequestBody ChatGroup chatGroup) throws Exception{
        ChatGroup cg = mongoTool.findOne("","{'id':"+precheck_id+",'qualityCheckAt':null,'deletedAt':null}", ChatGroup.class);
        if(cg != null){
            mongoTool.update("{'qualityCheckDate':'"+ymdhms.format(new Date(chatGroup.getQualityCheckAt()*1000))+"','qualityCheckAt':"+chatGroup.getQualityCheckAt()*1000+"}","{'id':"+precheck_id+"}",ChatGroup.class);
            pushService.sentStatusPush(cg);
            rongYunService.sentStatusMsg(cg,3);
            respData(ok);
        }else{
            respErr("PrecheckId Not Exist");
        }
    }
}
